﻿using InCom.API.Protocols;
using InCom.API.Protocols.Entitys;
using InCom.Utilities.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using InComRealtimeUpEntity = InCom.Entities.ProtocolEntity.RealtimeUpEntity;
using ApiRealtimeUpEntity = InCom.API.Protocols.Entitys.RealtimeUpEntity;

namespace InCom.Logic.Process.Translation
{

    /// <summary>
    /// 实时数据与incom.api相互转换代码
    /// </summary>
    public class TerminalRealtimeUpEntityTranslation
    {

        /// <summary>
        /// 将incomapi协议转换成为 incom的终端协议,如果转换失败则返回null
        /// </summary>
        /// <param name="incomAPiProtocol">协议数据</param>
        /// <param name="terminalEntity">终端数据实体</param>
        /// <returns>转换数据</returns>
        public TerminalBaseProtocolEntity GetTerminalEntity(BaseTcpProtocolEntity incomAPiProtocol)
        {
            TerminalBaseProtocolEntity udp = new InComRealtimeUpEntity()
            {
                //设置初始化值
                Afn = Afn,
            };
            //当前incom.api协议数据实体
            ApiRealtimeUpEntity apiProtocol = incomAPiProtocol as ApiRealtimeUpEntity;
            if (apiProtocol != null)
            {
                udp.TerminalCode = apiProtocol.TerminalCode;
                Resolve(apiProtocol, Afn);
            }
            return udp;
        }
        /// <summary>
        /// 传入终端协议,将终端协议转换成为,对应的incom.api协议
        /// </summary>
        /// <param name="terminalEntity">终端协议数据实体</param>
        /// <returns></returns>
        public BaseTcpProtocolEntity GetInComAPIEntity(TerminalBaseProtocolEntity terminalEntity, BaseTcpProtocolEntity incomAPiProtocol = null)
        {
            //当前incom.api协议数据实体
            ApiRealtimeUpEntity apiProtocol = null;
            apiProtocol = Resolve((InComRealtimeUpEntity)terminalEntity, incomAPiProtocol as ApiRealtimeUpEntity);
            apiProtocol.TerminalCode = terminalEntity.TerminalCode;

            return apiProtocol;
        }


        /// <summary>
        /// 对应的终端协议
        /// </summary>
        public byte Afn
        {
            get { return (byte)InCom.Utilities.Protocol.Afn.TERMINAL_DATA; }
        }

        #region 终端->incom.api协议
        /// <summary>
        /// 参数查询返回结果,从终端协议转换到incom.api协议
        /// </summary>
        /// <param name="unitEntity">传入数据单元对像</param>
        /// <param name="incomAPiProtocol">APi协议数据实体</param>
        /// <returns>返回对应的incom.api 数据项实体</returns>
        protected ApiRealtimeUpEntity Resolve(InComRealtimeUpEntity item, ApiRealtimeUpEntity incomAPiProtocol)
        {
            //需要返回到终端的值
            ApiRealtimeUpEntity apiProtocol = incomAPiProtocol;
            if (apiProtocol == null)
            {
                apiProtocol = new ApiRealtimeUpEntity()
                    {

                    };
            }

            #region 赋值

            apiProtocol.AccelerometerX = item.AccelerometerX;
            apiProtocol.AccelerometerY = item.AccelerometerY;
            apiProtocol.AccelerometerZ = item.AccelerometerZ;
            apiProtocol.AlarmBeginTime = item.AlarmBeginTime;
            apiProtocol.AlarmType = item.AlarmType;
            apiProtocol.Altitude = (decimal)item.Altitude;
            apiProtocol.AutoID = item.AutoId;
            apiProtocol.CANError = item.CanError;
            apiProtocol.ChargeDischarge = item.ChargeDischarge;
            apiProtocol.ClientDBCMD5Value = item.ClientDbcmd5Value;
            apiProtocol.Data = item.Data;
            apiProtocol.TravelTime = item.TravelTime;
            apiProtocol.DBCVariableNameCount = item.DbcVariableNameCount;
            apiProtocol.Destination = item.Destination;
            apiProtocol.DiagnosisResult = item.DiagnosisResult;
            apiProtocol.DynamicData = new byte[0];
            apiProtocol.ErrorCode = item.ErrorCode;
            apiProtocol.GPRSSignalStrength = item.GprsSignalStrength;
            apiProtocol.GPSCarSpeed = (decimal)item.GpsCarSpeed;
            apiProtocol.GPSData = new byte[0];
            apiProtocol.GPSDirection = (decimal)item.GpsDirection;
            apiProtocol.GPSMileage = (decimal)item.GpsMileage;
            apiProtocol.IsCache = item.IsCache;
            apiProtocol.IsCanHasData = item.IsCanHasData;
            apiProtocol.IsGPSPosition = item.IsGpsPosition;
            apiProtocol.IsHasDynamic = item.IsHasDynamic;
            apiProtocol.IsHypervelocity = item.IsHypervelocity;
            apiProtocol.IsLock = item.IsLock;
            apiProtocol.IsMainPowerExists = item.IsMainPowerExists;
            apiProtocol.IsRealtimeCoordinate = item.IsRealtimeCoordinate;
            apiProtocol.IsSlopOver = item.IsSlopOver;
            apiProtocol.IsTravel = item.IsTravel;
            apiProtocol.IsTriedDrive = item.IsTriedDrive;
            apiProtocol.IsVehicleHasFault = item.IsVehicleHasFault;
            apiProtocol.Latitude = (decimal)item.Latitude;
            apiProtocol.Longitude = (decimal)item.Longitude;
            apiProtocol.LockCarEquipmentState = item.LockCarEquipmentState;
            apiProtocol.PassthroughContext = new byte[0];
            apiProtocol.PassthroughMode = 0;
            apiProtocol.PassthroughSeq = 0;
            apiProtocol.PassthroughVersion = 0;
            apiProtocol.ResetNumber = item.ResetNumber;
            apiProtocol.SDCardError = item.SdCardError;
            ////////////////////////		=	item.	////////////////////////	,
            //IsMultiPacket = item.	//IsMultiPacket 	,
            //Length = item.	//Length 	,
            //MessageCurrentSEQ = item.	//MessageCurrentSEQ 	,
            //MessageTotalLength = item.	//MessageTotalLength 	,
            //MSGSEQ = item.	//MSGSEQ 	,
            //ProtocolUnitEntities = item.	//ProtocolUnitEntities 	,
            //ReceiveTime = item.	//ReceiveTime 	,
            //SendTime = item.	//SendTime 	,
            //SEQ = item.	//SEQ 	,
            //UserFlag = item.	//UserFlag 	,
            ///////////////////////////////////////		=	item.	///////////////////////////////////////	,
            apiProtocol.SleepMode = item.SleepMode;
            apiProtocol.StateParameters = item.StateParameters;
            apiProtocol.StatusData = new byte[0];
            apiProtocol.Switching = item.Switching;
            apiProtocol.Terminal_CIR_Temp = item.TerminalCirTemp;
            apiProtocol.TerminalCode = item.TerminalCode;
            apiProtocol.TerminalState = item.TerminalState;
            apiProtocol.Voltage1 = item.Voltage1;
            apiProtocol.Voltage2 = item.Voltage2;
            #region 基站,司机卡ID一汽项目使用
            /// <summary>
            /// 司机卡ID driverid      VARCHAR2(50),
            /// </summary>
            apiProtocol.Driverid = string.Empty;
            /// <summary>
            /// 基站编号 basestationid VARCHAR2(50)
            /// </summary>
            apiProtocol.BaseStationid = string.Empty;

            #endregion
            #region 天线信息
            /// <summary>
            /// GPS天线状态值,默认0没有初始化
            /// </summary>
            apiProtocol.AerialStatus = 0;
            #endregion

            #region wuwei 20160222 CAN2相关
            //can2信息赋值
            if (item.Can2ChargeEvent != null)
            {
                apiProtocol.RealExpand = ConvertCan2(item.Can2ChargeEvent);
            }
            #endregion
            // 终端累计行始时间 单位:秒
            apiProtocol.TotalRunningTime = item.TotalRunningTime;
            #endregion
            return apiProtocol;
        }

        #endregion

        /// <summary>
        /// 将终端的CAN2数据实体转为API的扩展数据实体
        /// </summary>
        /// <param name="item">CAN2数据实体</param>
        /// <returns>API扩展数据项</returns>
        private RealExpand ConvertCan2(InCom.Entities.ProtocolEntity.ChargeEvent item)
        {
            //构建返回值
            RealExpand result = new RealExpand() { Exmsg = item.EventType };
            //进行实体转换赋值
            switch (item.EventType)
            {
                //握手完成事件
                case 0x01:
                    var handevent = new HandShakeChargeEvent()
                    {
                        ProtocolType = 0x01,
                        ProtocolVer = 100,

                    };
                    var sourceentity = item as InCom.OTM.Entities.HandShakeChargeEvent;
                    ;
                    handevent.ReportTime = sourceentity.ReportTime;
                    handevent.Result = sourceentity.Result;
                    handevent.ChargeNumber = sourceentity.ChargeNumber;
                    handevent.ZipCode = sourceentity.ZipCode;
                    handevent.BMSConVer = sourceentity.BMSConVer;
                    handevent.BatteryType = sourceentity.BatteryType;
                    handevent.BatteryRatedCapacity = sourceentity.BatteryRatedCapacity;
                    handevent.BatteryRatedPressure = sourceentity.BatteryRatedPressure;
                    handevent.BatteryManufacturers = sourceentity.BatteryManufacturers;
                    handevent.BatteryPackNumber = sourceentity.BatteryPackNumber;
                    handevent.BatteryPackProductionDate = sourceentity.BatteryPackProductionDate;
                    handevent.BatteryPackChargeNumber = sourceentity.BatteryPackChargeNumber;
                    handevent.PropertyMark = sourceentity.PropertyMark;
                    handevent.VIN = sourceentity.VIN;
                    //赋值
                    result.Expand = handevent;
                    break;
                case 0x02:
                    var setevent = new SetCompleteChargeEvent()
                    {
                        ProtocolType = 0x01,
                        ProtocolVer = 100,
                    };
                    var sourceentity2 = item as InCom.OTM.Entities.SetCompleteChargeEvent;

                    setevent.ReportTime = sourceentity2.ReportTime;
                    setevent.单体动力蓄电池最高允许电压 = sourceentity2.单体动力蓄电池最高允许电压;
                    setevent.最高允许充电电流 = sourceentity2.最高允许充电电流;
                    setevent.最高允许充电总电压 = sourceentity2.最高允许充电总电压;
                    setevent.最高允许温度 = sourceentity2.最高允许温度;
                    setevent.动力蓄电池荷状态_动力蓄电池估计剩余容量 = sourceentity2.动力蓄电池荷状态_动力蓄电池估计剩余容量;
                    setevent.动力蓄电池总电压 = sourceentity2.动力蓄电池总电压;
                    setevent.最高输出电压 = sourceentity2.最高输出电压;
                    setevent.最低输出电压 = sourceentity2.最低输出电压;
                    setevent.最大输出电流 = sourceentity2.最大输出电流;
                    setevent.BMS是否准备好 = sourceentity2.BMS是否准备好;
                    setevent.充电机是否准备好 = sourceentity2.充电机是否准备好;
                    //赋值
                    result.Expand = setevent;
                    break;
                case 0x03:
                    var stateevent = new StateChargeEvent()
                    {
                        ProtocolType = 0x01,
                        ProtocolVer = 100,
                    };
                    var sourceentity3 = item as InCom.OTM.Entities.StateChargeEvent;

                    stateevent.ReportTime = sourceentity3.ReportTime;
                    stateevent.VoltageRequirement = sourceentity3.VoltageRequirement;
                    stateevent.CurrentDemand = sourceentity3.CurrentDemand;
                    stateevent.ChargingMode = sourceentity3.ChargingMode;
                    stateevent.ChargeVoltageMeasurement = sourceentity3.ChargeVoltageMeasurement;
                    stateevent.ChargeCurrentMeasurement = sourceentity3.ChargeCurrentMeasurement;
                    stateevent.CurrentStateOfChargeSOC = sourceentity3.CurrentStateOfChargeSOC;
                    stateevent.EstimatedRemainingChargingTime = sourceentity3.EstimatedRemainingChargingTime;
                    stateevent.VoltageOutputValue = sourceentity3.VoltageOutputValue;
                    stateevent.CurrentOutputValue = sourceentity3.CurrentOutputValue;
                    stateevent.CumulativeChargeTime = sourceentity3.CumulativeChargeTime;
                    stateevent.MaximumMonomerVoltage = sourceentity3.MaximumMonomerVoltage;
                    stateevent.TheHighestNumberOfSingleVoltage = sourceentity3.TheHighestNumberOfSingleVoltage;
                    stateevent.MaxMonomerVoltageNumber = sourceentity3.MaxMonomerVoltageNumber;
                    stateevent.MaximumBatteryTemperature = sourceentity3.MaximumBatteryTemperature;
                    stateevent.MaximumTemperatureTestPointNumber = sourceentity3.MaximumTemperatureTestPointNumber;
                    stateevent.MinimumBatteryTemperature = sourceentity3.MinimumBatteryTemperature;
                    stateevent.MinimumBatteryTemperatureNumber = sourceentity3.MinimumBatteryTemperatureNumber;
                    stateevent.TheBatteryVoltageIsTooHigh_TooLow = sourceentity3.TheBatteryVoltageIsTooHigh_TooLow;
                    stateevent.SOCHigh_LowPowerBattery = sourceentity3.SOCHigh_LowPowerBattery;
                    stateevent.PowerBatteryChargingOverCurrent = sourceentity3.PowerBatteryChargingOverCurrent;
                    stateevent.PowerBatteryTemperatureIsTooHigh = sourceentity3.PowerBatteryTemperatureIsTooHigh;
                    stateevent.PowerStorageBatteryInsulation = sourceentity3.PowerStorageBatteryInsulation;
                    stateevent.PowerBatteryOutputConnectorStatus = sourceentity3.PowerBatteryOutputConnectorStatus;
                    stateevent.ChargingPermit = sourceentity3.ChargingPermit;
                    //赋值
                    result.Expand = stateevent;
                    break;
                case 0x04:
                    var endevent = new EndChargeEvent()
                    {
                        ProtocolType = 0x01,
                        ProtocolVer = 100,
                    };
                    var sourceentity4 = item as InCom.OTM.Entities.EndChargeEvent;

                    endevent.ReportTime = sourceentity4.ReportTime;
                    endevent.BMSReasonsForSuspensionOfCharging = sourceentity4.BMSReasonsForSuspensionOfCharging;
                    endevent.BMSReasonsForTheFailureToSuspendTheCharging =
                        sourceentity4.BMSReasonsForTheFailureToSuspendTheCharging;
                    endevent.ReasonsForBMSAbortChargingError = sourceentity4.ReasonsForBMSAbortChargingError;
                    endevent.TheReasonToStopChargingCharger = sourceentity4.TheReasonToStopChargingCharger;
                    endevent.StopChargingChargerFailure = sourceentity4.StopChargingChargerFailure;
                    endevent.ChargerToStopChargingErrors = sourceentity4.ChargerToStopChargingErrors;
                    endevent.AbortSOC = sourceentity4.AbortSOC;
                    endevent.MonomerMinimumVoltage = sourceentity4.MonomerMinimumVoltage;
                    endevent.SingleMaximumVoltage = sourceentity4.SingleMaximumVoltage;
                    endevent.MinimumTemperature = sourceentity4.MinimumTemperature;
                    endevent.MaximumTemperature = sourceentity4.MaximumTemperature;
                    endevent.CumulativeChargeTime = sourceentity4.CumulativeChargeTime;
                    endevent.OutputEnergy = sourceentity4.OutputEnergy;
                    endevent.ChargerNumber = sourceentity4.ChargerNumber;
                    //赋值
                    result.Expand = endevent;
                    break;
                case 0x0F:
                    var errorevent = new ErrorChargeEvent()
                    {
                        ProtocolType = 0x01,
                        ProtocolVer = 100,
                    };
                    var sourceentity5 = item as InCom.OTM.Entities.ErrorChargeEvent;

                    errorevent.ReportTime = sourceentity5.ReportTime;
                    errorevent.BMSErrorStatus = sourceentity5.BMSErrorStatus;
                    errorevent.ChargerErrorStatus = sourceentity5.ChargerErrorStatus;
                    errorevent.BatteryFaultStatus = sourceentity5.BatteryFaultStatus;
                    errorevent.BMSFaultCode = sourceentity5.BMSFaultCode;
                    errorevent.ChargerFailure = sourceentity5.ChargerFailure;
                    //赋值
                    result.Expand = errorevent;
                    break;
            }
            return result;
        }


        #region incom.api ->终端
        /// <summary>
        /// 解析实时数据协议 incom.api ->终端
        /// </summary>
        /// <param name="unitEntity"></param>
        /// <param name="afn"></param>
        /// <returns></returns>
        protected InComRealtimeUpEntity Resolve(ApiRealtimeUpEntity item, byte afn)
        {

            InComRealtimeUpEntity incomProtocol = new InComRealtimeUpEntity()
                    {
                        Afn = afn,
                        #region 赋值
                        AccelerometerX = item.AccelerometerX,
                        AccelerometerY = item.AccelerometerY,
                        AccelerometerZ = item.AccelerometerZ,
                        AlarmBeginTime = item.AlarmBeginTime,
                        AlarmType = item.AlarmType,
                        Altitude = (double)item.Altitude,
                        AutoId = item.AutoID,
                        CanError = item.CANError,
                        ChargeDischarge = item.ChargeDischarge,
                        ClientDbcmd5Value = item.ClientDBCMD5Value,
                        Data = item.Data,
                        TravelTime = item.TravelTime,
                        DbcVariableNameCount = (ushort)item.DBCVariableNameCount,
                        Destination = item.Destination,
                        DiagnosisResult = item.DiagnosisResult,
                        //DynamicData = item.DynamicData,
                        ErrorCode = item.ErrorCode,
                        GprsSignalStrength = item.GPRSSignalStrength,
                        GpsCarSpeed = (double)item.GPSCarSpeed,
                        //GPSData = item.GPSData,
                        GpsDirection = (double)item.GPSDirection,
                        GpsMileage = (double)item.GPSMileage,
                        IsCache = item.IsCache,
                        IsCanHasData = item.IsCanHasData,
                        IsGpsPosition = item.IsGPSPosition,
                        IsHasDynamic = item.IsHasDynamic,
                        IsHypervelocity = item.IsHypervelocity,
                        IsLock = item.IsLock,
                        IsMainPowerExists = item.IsMainPowerExists,
                        IsRealtimeCoordinate = item.IsRealtimeCoordinate,
                        IsSlopOver = item.IsSlopOver,
                        IsTravel = item.IsTravel,
                        IsTriedDrive = item.IsTriedDrive,
                        IsVehicleHasFault = item.IsVehicleHasFault,
                        Latitude = (double)item.Latitude,
                        Longitude = (double)item.Longitude,
                        LockCarEquipmentState = item.LockCarEquipmentState,
                        //PassthroughContext = item.PassthroughContext,
                        //PassthroughMode = item.PassthroughMode,
                        //PassthroughSeq = item.PassthroughSeq,
                        //PassthroughVersion = item.PassthroughVersion,
                        ResetNumber = item.ResetNumber,
                        SdCardError = item.SDCardError,
                        ////////////////////////		=	item.	////////////////////////	,
                        //IsMultiPacket = item.	//IsMultiPacket 	,
                        //Length = item.	//Length 	,
                        //MessageCurrentSEQ = item.	//MessageCurrentSEQ 	,
                        //MessageTotalLength = item.	//MessageTotalLength 	,
                        //MSGSEQ = item.	//MSGSEQ 	,
                        //ProtocolUnitEntities = item.	//ProtocolUnitEntities 	,
                        //ReceiveTime = item.	//ReceiveTime 	,
                        //SendTime = item.	//SendTime 	,
                        //SEQ = item.	//SEQ 	,
                        //UserFlag = item.	//UserFlag 	,
                        ///////////////////////////////////////		=	item.	///////////////////////////////////////	,
                        SleepMode = item.SleepMode,
                        StateParameters = item.StateParameters,
                        // StatusData = item.StatusData,
                        Switching = item.Switching,
                        TerminalCirTemp = item.Terminal_CIR_Temp,
                        TerminalCode = item.TerminalCode,
                        TerminalState = item.TerminalState,
                        Voltage1 = item.Voltage1,
                        Voltage2 = item.Voltage2,
                        #region 基站,司机卡ID一汽项目使用
                        /// <summary>
                        /// 司机卡ID driverid      VARCHAR2(50),
                        /// </summary>
                        //Driverid = item.Driverid,
                        /// <summary>
                        /// 基站编号 basestationid VARCHAR2(50)
                        /// </summary>
                        // BaseStationid = item.BaseStationid,

                        #endregion
                        //GPS天线状态
                        //AerialStatus = item.AerialStatus,
                        // 终端累计行始时间 单位:秒
                        TotalRunningTime = (uint)item.TotalRunningTime,
                        #endregion
                    };

            return incomProtocol;
        }
        #endregion







        /// <summary>
        /// 版本号
        /// </summary>
        public int Ver
        {
            get { return 0; }
        }

        private static string summary = "实时数据转换";
        /// <summary>
        /// 返回当前项的描述信息
        /// </summary>
        public string Summary
        {
            get { return summary; }
        }

        /// <summary>
        /// 消息号
        /// </summary>
        public ushort MSGSEQ { get { return (ushort)APIProtocolType.REALTIMEDATA; } }




    }
}
